package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
)

/*
对于商品的操作包括

	搜索
	添加
	更新
	删除
*/
const goodsMapping = `
{
	"mappings":{
		"properties":{
			"name":{
				"type":"text",
				"analyzer": "ik_max_word"
			},
			"id":{
				"type":"integer"
			}
		}
	}
}`

type Account struct {
	AccountNumber int32  `json:"account_number"`
	FirstName     string `json:"firstname"`
}

func main() {
	// 初始化一个连接
	host := "http://192.168.16.109:9200"
	// 这里必须将 sniff 设置为 false, 因为使用 olivere/elastic 连接 elasticsearch 时, 发现连接地址明明输入的时候是网地址,
	// 但是连接时会自动转换成内网地址或者docker中的 ip 地址, 导致服务连接不上
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	client, err := elastic.NewClient(
		elastic.SetURL(host),
		elastic.SetBasicAuth("elastic", "56248Qwezxcv"),
		elastic.SetSniff(false),
		elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}

	q := elastic.NewMatchQuery("address", "street")
	result, err := client.Search().Index("user").Query(q).Do(context.Background())
	if err != nil {
		panic(err)
	}
	total := result.Hits.TotalHits.Value
	fmt.Printf("搜索结果数量: %d\n", total)
	for _, value := range result.Hits.Hits {
		account := Account{}
		err := json.Unmarshal(value.Source, &account)
		if err != nil {
			return
		}
		fmt.Println(account)
	}

	//// Index a tweet (using JSON serialization)
	//tweet1 := Account{AccountNumber: 15368, FirstName: "czc learn"}
	//put1, err := client.Index().Index("myuser").BodyJson(tweet1).Do(context.Background())
	//if err != nil {
	//	// Handle error
	//	panic(err)
	//}
	//fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)

	_, err = client.CreateIndex("mygoods").BodyString(goodsMapping).Do(context.Background())
	if err != nil {
		panic(err)
	}

}
